#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import sys

import cv2
import numpy as np
from matplotlib import pyplot as plt

# img = cv2.imread('temp_player.jpg', cv2.IMREAD_COLOR)
# color = ('b', 'g', 'r')
# for i, col in enumerate(color):
#     histr = cv2.calcHist([img], [i], None, [256], [0, 256])
#     plt.plot(histr, color=col)

template = cv2.imread('template.png')
img = cv2.imread('images/00000_1514972261.png')


def getFilteredImg(img):
    # hsv2 = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    # FILTER_MIN = np.array([100, 50, 20], np.uint8)
    # FILTER_MAX = np.array([150, 120, 150], np.uint8)
    hsv2 = img
    FILTER_MIN = np.array([50, 39, 40], np.uint8)
    FILTER_MAX = np.array([110, 76, 76], np.uint8)
    frame_threshed = cv2.inRange(hsv2, FILTER_MIN, FILTER_MAX)
    # frame_threshed2 = cv2.cvtColor(frame_threshed, cv2.COLOR_HSV2BGR)
    result = cv2.bitwise_or(img, img, mask=frame_threshed)
    return result

template = getFilteredImg(template)
img = getFilteredImg(img)

plt.subplot(131), plt.imshow(template)
plt.show()

# plt.subplot(132), plt.imshow(img)
#
# h = template.shape[0]
# w = template.shape[1]
# res = cv2.matchTemplate(img, template, cv2.TM_SQDIFF_NORMED)
# min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)
# print("min_val: {}, max_val: {}".format(min_val, max_val))
# cv2.circle(img, min_loc, 3, (255, 0, 0), -1)
# cv2.circle(img, max_loc, 3, (255, 0, 0), -1)
# top_left = min_loc
# bottom_right = (top_left[0] + w, top_left[1] + h)
# print("min_loc: {}, bottom_right: {}".format(min_loc, bottom_right))
#
# cv2.rectangle(img, top_left, bottom_right, 255, 2)
#
# plt.subplot(133), plt.imshow(img)
# plt.show()
#
# sys.exit(0)

# print(hsv2)
# hist = cv2.calcHist([hsv2], [0, 1], None, [180, 256], [0, 180, 0, 256])
# hsv2 = cv2.cvtColor(template, cv2.COLOR_BGR2HSV)
hsv2 = template
histH = cv2.calcHist([hsv2], [0], None, [256], [0, 256])
histS = cv2.calcHist([hsv2], [1], None, [256], [0, 256])
histV = cv2.calcHist([hsv2], [2], None, [256], [0, 256])
plt.plot(histH, color='r')
plt.plot(histS, color='g')
plt.plot(histV, color='b')
plt.xlim([1, 256])
# plt.imshow(hist,interpolation = 'nearest')
plt.show()

sys.exit(0)
